package com.fenxiao.base;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;


@SuppressWarnings("unchecked")
public abstract class BaseDaoImpl<T> implements BaseDao<T> {

	@Resource
	private SessionFactory sessionFactory;
	private Class<T> clazz;

	public BaseDaoImpl() {

		ParameterizedType pt = (ParameterizedType) this.getClass()
				.getGenericSuperclass(); 
		this.clazz = (Class<T>) pt.getActualTypeArguments()[0]; 

		System.out.println("clazz ---> " + clazz);
	}

	protected Session getSession() {
		// sessionFactory.openSession();
		return sessionFactory.getCurrentSession();
	}

	public void save(T entity) {
		getSession().save(entity);
	}

	public void update(T entity) {
		getSession().update(entity);
	}

	public void delete(Integer id) {
		Object obj = getById(id);
		if (obj != null) {
			getSession().delete(obj);
		}
	}

	public T getById(Integer id) {
		return (T) getSession().get(clazz, id);
	}

	public List<T> findAll() {
		List<T> list = getSession().createQuery(//
				"FROM " + clazz.getSimpleName())//
				.list();

		return list;
	}

	//
	public List<T> getByIds(Integer[] ids) {
		if (ids == null || ids.length == 0) {
			return null;
		} else {
			return getSession().createQuery(//
					"FROM " + clazz.getSimpleName() + " WHERE id IN (:ids)")//
					.setParameterList("ids", ids)//
					.list();
		}
	}

	/*public PageBean<T> getPageBean(int page, int limit, String hql,List<Object> parameters) {
		PageBean<T> pageBean = new PageBean<T>();

		Query listQuery = getSession().createQuery(hql); // 创建查询对象
		if (parameters != null) { // 设置参数
			for (int i = 0; i < parameters.size(); i++) {
				listQuery.setParameter(i, parameters.get(i));
			}
		}

		listQuery.setFirstResult((page - 1) * limit);
		listQuery.setMaxResults(limit);
		List list = listQuery.list(); // 执行查询

		// 查询总记录数量
		Query countQuery = getSession().createQuery("SELECT COUNT(*) " + hql);
		if (parameters != null) { // 设置参数
			for (int i = 0; i < parameters.size(); i++) {
				countQuery.setParameter(i, parameters.get(i));
			}
		}
		
		Long count1 =(Long) countQuery.uniqueResult();
		int count =new Long(count1).intValue();
		
		pageBean.setPage(page);
		pageBean.setTotalCount(count);
		pageBean.setLimit(limit);
		pageBean.setList(list);
		int totalPage = 0;
		if (count % limit == 0) {
			totalPage = count / limit;
		} else {
			totalPage = count / limit + 1;
		}
		pageBean.setTotalPage(totalPage);
		return pageBean;
	}
	*/
}
